import time
import os
import csv

def calculate_BMR(gender, height, age, weight):
    if gender == '男':
        BMR = 88.362 + (13.397 * weight) + (4.799 * height) - (5.677 * age)
    elif gender == '女':
        BMR = 447.593 + (9.247 * weight) + (3.098 * height) - (4.330 * age)
    else:
        return None
    return BMR

def get_valid_input(prompt, check_func):
    while True:
        value = input(prompt)
        if check_func(value):
            return value
        print("输入有误，请重新输入！")

def count():
    gender = get_valid_input("请输入性别（男/女）：", lambda x: x in ['男', '女'])   
    try:
        height = float(get_valid_input("请输入身高（单位：cm）：", str.isdigit))
        age = int(get_valid_input("请输入年龄（岁）：", str.isdigit))
        weight = float(get_valid_input("请输入体重（单位：kg）：", str.isdigit))
    except ValueError:
        print("输入有误，请重新输入！")
        return

    BMR = calculate_BMR(gender, height, age, weight)
    if BMR is None:
        print("性别输入有误，请重新输入！")
    else:
        print("您的BMR值为：{:.2f}".format(BMR))
    if BMR < 1200:
        print("您的BMR值过低！BMR值正常范围为1200-2100")
    elif 1200 < BMR < 2100:
        print("您的BMR值正常！")
    elif BMR > 2100:
        print("您的BMR值过高！BMR值正常范围为1200-2100")

        filename = 'BMR记录.csv'
        try:
            if not os.path.exists(filename):
                with open(filename, 'w', newline='') as f:
                    writer = csv.writer(f)
                    writer.writerow(['时间', '性别', '身高(cm)', '年龄(岁)', '体重(kg)', 'BMR值(千卡/天)'])
            with open(filename, 'a', newline='') as f:
                writer = csv.writer(f)
                writer.writerow([time.strftime('%Y-%m-%d %H:%M:%S'), gender, height, age, weight, BMR])
        except IOError as e:
            print("写入CSV文件时出错：", e)

if __name__ == '__main__':
    while True:
        print("欢迎使用BMR计算器！")
        count()
        print('---------------------------')
        choice = get_valid_input("已完成所有输入，是否退出：", lambda x: x in ['是', '否'])
        if choice == '是':
            print("感谢使用BMR计算器！")
            break  
        else:
            continue